<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';

// Props
interface Props {
  modelValue?: number;
  selectedRange: number[];
  disabled?: boolean;
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: number): void;
  (e: 'change', value: number): void;
  (e: 'displayToggle', enabled: boolean): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: 737,
  selectedRange: () => [-3200, 1900],
  disabled: false,
});
const emit = defineEmits<Emits>();
// 响应式数据
const isOpen = ref(false);
const searchQuery = ref('');
const selectedYear = ref(props.modelValue);

// 生成年份数组
const generateYears = (): number[] => {
  const years: number[] = [];

  // -3200 ~ -2000：每50年
  for (let year = -3200; year <= -2000; year += 50) {
    years.push(year);
  }

  // -1990 ~ -1000：每10年
  for (let year = -1990; year <= -1000; year += 10) {
    years.push(year);
  }

  // -999 ~ 1900：每年
  for (let year = -999; year <= 1900; year++) {
    if (year === 0) continue;
    years.push(year);
  }

  return years;
};

const allYears = ref<number[]>(generateYears());

const formatDisplayYear = (year: number): string => {
  return year < 0 ? `${Math.abs(year)} BC` : year.toString();
};

// 计算属性
const filteredYears = computed(() => {
  if (!searchQuery.value) {
    return allYears.value;
  }

  const query = searchQuery.value.toLowerCase();
  return allYears.value.filter((year) => {
    const displayYear = formatDisplayYear(year);
    return displayYear.toLowerCase().includes(query);
  });
});

const toggleDropdown = () => {
  if (!props.disabled) {
    isOpen.value = !isOpen.value;
  }
};

const selectYear = (year: number) => {
  selectedYear.value = year;
  isOpen.value = false;
  searchQuery.value = '';
  emit('update:modelValue', year);
  emit('change', year);
};
const dropdownRef = ref<HTMLElement | null>(null);

const closeDropdown = (event: Event) => {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target as Node)) {
    isOpen.value = false;
  }
};

watch(
  () => props.modelValue,
  (newValue) => {
    if (selectedYear.value !== newValue) {
      selectedYear.value = newValue;
    }
  },
);

watch(
  () => props.selectedRange,
  (newRange) => {
    const newEndYear = newRange[1];

    // 找到离 newEndYear 最近的一个 year（不使用 reduce）
    let closestYear = allYears.value[0];
    let minDiff = Math.abs(allYears.value[0] - newEndYear);

    for (const year of allYears.value) {
      const diff = Math.abs(year - newEndYear);
      if (diff < minDiff) {
        minDiff = diff;
        closestYear = year;
      }
    }

    if (selectedYear.value !== closestYear) {
      selectedYear.value = closestYear;
      emit('update:modelValue', closestYear);
      emit('change', closestYear);
    }
  },
  { immediate: true },
);

onMounted(() => {
  document.addEventListener('click', closeDropdown);
});

onUnmounted(() => {
  document.removeEventListener('click', closeDropdown);
});

// 监听 props 变化
watch(
  () => props.modelValue,
  (newValue) => {
    selectedYear.value = newValue;
  },
);
</script>

<template>
  <div
    ref="dropdownRef"
    class="fixed right-16 top-16 z-50 inline-block text-left"
  >
    <!-- 下拉框触发器 -->
    <div>
      <button
        type="button"
        @click="toggleDropdown"
        class="inline-flex w-full items-center justify-between rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
        :class="{ 'ring-2 ring-indigo-500': isOpen }"
      >
        <div class="flex items-center space-x-2">
          <svg
            class="h-4 w-4 text-gray-500"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
          <span>疆域时间: {{ formatDisplayYear(selectedYear) }}</span>
        </div>

        <svg
          class="h-5 w-5 text-gray-400 transition-transform duration-200"
          :class="{ 'rotate-180': isOpen }"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </button>
    </div>

    <!-- 下拉菜单 -->
    <transition
      enter-active-class="transition-all duration-300 ease-out overflow-hidden"
      enter-from-class="max-h-0 opacity-0"
      enter-to-class="max-h-96 opacity-100"
      leave-active-class="transition-all duration-200 ease-in overflow-hidden"
      leave-from-class="max-h-96 opacity-100"
      leave-to-class="max-h-0 opacity-0"
    >
      <div
        v-if="isOpen"
        class="absolute right-0 z-10 mt-2 w-2/3 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
      >
        <div class="max-h-62 overflow-y-auto py-1">
          <!-- 搜索框 -->
          <div class="border-b border-gray-100 px-3 py-2">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索年份..."
              class="w-full rounded border border-gray-300 px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />
          </div>

          <!-- 年份选项 -->
          <div class="scrollbar-overlay max-h-48 overflow-y-auto">
            <button
              v-for="year in filteredYears"
              :key="year"
              @click="selectYear(year)"
              class="flex-center h-8 w-full px-4 py-2 text-center text-sm hover:bg-gray-100 focus:bg-gray-100 focus:outline-none"
              :class="{
                'bg-indigo-50 text-indigo-700': year === selectedYear,
                'text-gray-900': year !== selectedYear,
              }"
            >
              {{ formatDisplayYear(year) }}
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<style lang="scss" scoped>
.scrollbar-overlay {
  scrollbar-color: rgb(0 0 0 / 30%) transparent;
  scrollbar-width: thin; /* Firefox */
}

.scrollbar-overlay::-webkit-scrollbar {
  position: absolute;
  width: 8px;
}

.scrollbar-overlay::-webkit-scrollbar-track {
  background: transparent;
}

.scrollbar-overlay::-webkit-scrollbar-thumb {
  background-color: rgb(0 0 0 / 30%);
  border-radius: 4px;
}
</style>
